package com.jinyu.jyly.ui.mall;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.jinyu.jyly.R;
import com.jinyu.jyly.adapter.MallPageTabAdapter;
import com.jinyu.jyly.adapter.MallTabAdapter;
import com.jinyu.jyly.base.BaseLazyFragment;
import com.jinyu.jyly.bean.AllInfoBean;
import com.jinyu.jyly.bean.MallListInfo;
import com.jinyu.jyly.bean.MallPageListInfo;
import com.jinyu.jyly.event.SeachNoticeEvent;
import com.jinyu.jyly.ui.mall.detail.MallDetailActivity;
import com.jinyu.jyly.utils.AES;
import com.jinyu.jyly.view.GridSpacingItemDecoration;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

/**
 *
 * @author 62485
 */
public class MallTabFragment extends BaseLazyFragment<MallPresenter> implements MallContract.View, BaseQuickAdapter.OnItemChildClickListener,BaseQuickAdapter.OnItemClickListener{

    @BindView(R.id.rcv_recycleview)
    RecyclerView rcv_recycleview;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout mRefreshLayout;
    @BindView(R.id.cl_empty)
    ConstraintLayout rl_empty;
    private boolean hasLoadMore = false;
    private boolean isFristLoad = true;
    private int PAGE_NO = 1;
    private int PAGE_SIZE = 10;
    private MallPresenter mPresenter;
    private int cid;
    private MallPageTabAdapter mallListPageAdapter;
    private GridSpacingItemDecoration itemDecoration;


    public static MallTabFragment newInstance(int type) {
        MallTabFragment newFragment = new MallTabFragment();
        Bundle bundle = new Bundle();
        bundle.putInt("type", type);
        newFragment.setArguments(bundle);
        return newFragment;
    }


    @Override
    protected View initView(ViewGroup container) {
        View view = LayoutInflater.from(mContext).inflate(R.layout.fragment_mall_tab, container, false);
        EventBus.getDefault().register(this);
        return view;
    }

    @Override
    protected void loadData() {
        initIntent();
        initRecycleview();
    }

    private void initIntent() {
        Bundle arguments = getArguments();
        cid = arguments.getInt("type", 1);
        getMallList();
    }

    private void getMallList() {
        try {
            mTipDialog.show();
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("cid", cid);
            jsonObject.put("page", PAGE_NO);
            String pamam = AES.encryptToHexString(jsonObject.toString());
//            mPresenter.getGoodList(pamam);

            mPresenter.getPageGoodList(pamam);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private void initRecycleview() {
//        rcv_recycleview.setNestedScrollingEnabled(false);
        rcv_recycleview.setLayoutManager(new GridLayoutManager(getActivity(), 2));
        mRefreshLayout.setEnableRefresh(false);//是否启用下拉刷新功能

        if(itemDecoration==null){
            itemDecoration = new GridSpacingItemDecoration(2, 45, false);
            rcv_recycleview.addItemDecoration(new GridSpacingItemDecoration(2, 45, false));
        }

        mRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull final RefreshLayout refreshLayout) {
                PAGE_NO = 1;
                try {
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("cid", cid);
                    jsonObject.put("page",PAGE_NO);
                    String pamam = AES.encryptToHexString(jsonObject.toString());
//                    mPresenter.getGoodList(pamam);
                    mPresenter.getPageGoodList(pamam);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                hasLoadMore = false;
            }
        });

        mRefreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull final RefreshLayout refreshLayout) {
                ++PAGE_NO;
                try {
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("cid", cid);
                    jsonObject.put("page",PAGE_NO);
                    String pamam = AES.encryptToHexString(jsonObject.toString());
//                    mPresenter.getGoodList(pamam);
                    mPresenter.getPageGoodList(pamam);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                hasLoadMore = true;
            }
        });
    }

    @Override
    public MallPresenter getPresenter() {
        if(mPresenter == null){
            mPresenter = new MallPresenter(getActivity(), this);
        }
        return mPresenter;
    }



    /**
     * 刷新的时候
     * @param
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(SeachNoticeEvent event) {
        if (event != null) {
            try {
                PAGE_NO = 1;
                isFristLoad = true;
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("cid", cid);
                jsonObject.put("page",PAGE_NO);
                String pamam = AES.encryptToHexString(jsonObject.toString());
//                mPresenter.getGoodList(pamam);
                mPresenter.getPageGoodList(pamam);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }


    @Override
    public void onFailer(Throwable throwable) {
        mTipDialog.dismiss();
        mRefreshLayout.finishLoadMore();
        mRefreshLayout.finishRefresh();
        mRefreshLayout.resetNoMoreData();
    }

    @Override
    public void onSiteAd(AllInfoBean info) {
        mTipDialog.dismiss();
    }

    @Override
    public void onGoodsTypes(AllInfoBean infoBean) {
        mTipDialog.dismiss();
    }

    @Override
    public void onGoodList(AllInfoBean infoBean) {
        mTipDialog.dismiss();
        mRefreshLayout.finishLoadMore();
        mRefreshLayout.finishRefresh();
        mRefreshLayout.resetNoMoreData();
        switch (infoBean.getStatus()){
            case 200:
                String data = infoBean.getData();
                try {
                    String decrypt = AES.decrypt(data);
                    Gson gson = new Gson();
                    Type listType = new TypeToken<ArrayList<MallListInfo>>() {}.getType();
                    List<MallListInfo> mList = gson.fromJson(decrypt, listType);

                    if(mList != null && mList.size() != 0){
                        rcv_recycleview.setVisibility(View.VISIBLE);
                        rl_empty.setVisibility(View.GONE);
                        MallTabAdapter mallListAdapter = new MallTabAdapter(mList,R.layout.item_mall_tab);
                        rcv_recycleview.setAdapter(mallListAdapter);
                        mallListAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                            @Override
                            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                                MallListInfo mallListInfo = mList.get(position);
                                if(mallListInfo != null){
                                    int id = mallListInfo.getId();
                                    Intent mMallDetailIntent = new Intent(getActivity(), MallDetailActivity.class);
                                    mMallDetailIntent.putExtra("id",id);
                                    startActivity(mMallDetailIntent);
                                }
                            }
                        });
                    }else{
                        rcv_recycleview.setVisibility(View.GONE);
                        rl_empty.setVisibility(View.VISIBLE);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            case 422:
                showToast(infoBean.getMsg());
                break;
            default:break;
        }
    }

    @Override
    public void onGetTimes(AllInfoBean infoBean) {
        mTipDialog.dismiss();
    }

    /**
     * 获取商品列表(新)
     * @param infoBean
     */
    @Override
    public void onPageGoodList(AllInfoBean infoBean) {
        mTipDialog.dismiss();
        mRefreshLayout.finishLoadMore();
        mRefreshLayout.finishRefresh();
        mRefreshLayout.resetNoMoreData();
        switch (infoBean.getStatus()){
            case 200:
                String data = infoBean.getData();
                try {
                    String decrypt = AES.decrypt(data);
                    Gson gson = new Gson();
                    MallPageListInfo mallPageListInfo = gson.fromJson(decrypt, MallPageListInfo.class);
                    if(mallPageListInfo != null){
                        int page = mallPageListInfo.getPage();

                        if(isFristLoad){
                            List<MallPageListInfo.DataBean> data1List = mallPageListInfo.getData();
                            mallListPageAdapter = new MallPageTabAdapter(data1List,R.layout.item_mall_tab);
                            rcv_recycleview.setAdapter(mallListPageAdapter);
                            mallListPageAdapter.setOnItemClickListener(this);
                            isFristLoad = false;
                        }else{
                            if(!hasLoadMore){
                                //下拉加载
                                List<MallPageListInfo.DataBean> data1List = mallPageListInfo.getData();
                                mallListPageAdapter.replaceData(data1List);
                            }else{
                                //上拉加载
                                if (PAGE_NO <= page) {
                                    //说明有值
                                    List<MallPageListInfo.DataBean> data1List = mallPageListInfo.getData();
                                    mallListPageAdapter.addData(data1List);
                                }
                            }
                        }
                    }

                    List<MallPageListInfo.DataBean> data1List = mallListPageAdapter.getData();
                    if(data1List != null && data1List.size() != 0){
                        rcv_recycleview.setVisibility(View.VISIBLE);
                        rl_empty.setVisibility(View.GONE);
                    }else{
                        rcv_recycleview.setVisibility(View.GONE);
                        rl_empty.setVisibility(View.VISIBLE);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            case 422:
                showToast(infoBean.getMsg());
                break;
            default:break;
        }
    }


    @Override
    public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {

    }

    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
        if(mallListPageAdapter != null){
            List<MallPageListInfo.DataBean> dataList = mallListPageAdapter.getData();
            if(dataList != null && dataList.size()!=0){
                MallPageListInfo.DataBean dataBean = dataList.get(position);
                if (dataBean != null) {
                    int id = dataBean.getId();
                    Intent mMallDetailIntent = new Intent(getActivity(), MallDetailActivity.class);
                    mMallDetailIntent.putExtra("id", id);
                    startActivity(mMallDetailIntent);
                }
            }
        }
    }
}
